<template>
	<div>
		<div class="TUIChat" :class="[!isPC ? 'TUIChat-H5' : '']">
			<div class="TUIChat-main">
				<!-- <div class="TUIChat-safe-tips">
        <span>
          {{
            TUITranslateService.t(
              "TUIChat.【安全提示】本 APP 仅用于体验腾讯云即时通信 IM 产品功能，不可用于业务洽谈与拓展。请勿轻信汇款、中奖等涉及钱款的信息，勿轻易拨打陌生电话，谨防上当受骗。"
            )
          }}
        </span>
        <a @click="openComplaintLink(Link.complaint)">{{
          TUITranslateService.t("TUIChat.点此投诉")
        }}</a>
      </div> -->
				<div class="TUIChat-application-tips" v-if="isGroup && groupApplicationCount > 0"
					@click="toggleApplicationList()">
					<span>{{ groupApplicationCount }}
						{{ TUITranslateService.t("TUIChat.条入群申请") }}
						<span class="application-tips-btn">{{
            TUITranslateService.t("TUIChat.点击处理")
          }}</span>
					</span>
				</div>
				<scroll-view id="messageScrollList" class="TUI-message-list" scroll-y="true" :scroll-top="scrollTop"
					@scroll="handelScrollListScroll">
					<p v-if="!isCompleted" class="message-more" @click="getHistoryMessageList">
						{{ TUITranslateService.t("TUIChat.查看更多") }}
					</p>
					<li v-for="(item, index) in messageList" :id="`tui-${item.ID}`" :key="item.vueForRenderKey"
						:class="'message-li ' + item.flow">
						<MessageTimestamp :currTime="item.time" :prevTime="index > 0 ? messageList[index - 1].time : 0">
						</MessageTimestamp>
						<div class="message-item" @click.stop="toggleID = ''">
							<!-- 群创建提示 -->
							<MessageTip v-if="
                item.type === TYPES.MSG_GRP_TIP ||
                isCreateGroupCustomMessage(item)
              " :content="item.getMessageContent()" />
			  
							<div v-else-if="!item.isRevoked && !isPluginMessage(item)" :id="`msg-bubble-${item.ID}`"
								class="message-bubble-container"
								@longpress="handleToggleMessageItem($event, item, index, false)"
								@touchstart="handleH5LongPress($event, item, index, 'touchstart')"
								@touchend="handleH5LongPress($event, item, index, 'touchend')"
								@mouseover="handleH5LongPress($event, item, index, 'touchend')">
								<MessageBubble :messageItem="item" :content="item.getMessageContent()"
									:blinkMessageIDList="blinkMessageIDList" @resendMessage="resendMessage(item)"
									@blinkMessage="blinkMessage" @scrollTo="scrollTo"
									@setReadReciptPanelVisible="setReadReciptPanelVisible">
									<MessageText v-if="item.type === TYPES.MSG_TEXT"
										:content="item.getMessageContent()" />
									<ProgressMessage v-if="item.type === TYPES.MSG_IMAGE"
										:content="item.getMessageContent()" :messageItem="item">
										<MessageImage :content="item.getMessageContent()" :messageItem="item"
											@previewImage="handleImagePreview" />
									</ProgressMessage>
									<ProgressMessage v-if="item.type === TYPES.MSG_VIDEO"
										:content="item.getMessageContent()" :messageItem="item">
										<MessageVideo :content="item.getMessageContent()" :messageItem="item" />
									</ProgressMessage>
									<MessageAudio v-if="item.type === TYPES.MSG_AUDIO"
										:content="item.getMessageContent()" :messageItem="item"
										:broadcastNewAudioSrc="broadcastNewAudioSrc"
										@getGlobalAudioContext="getGlobalAudioContext" />
									<MessageFile v-if="item.type === TYPES.MSG_FILE"
										:content="item.getMessageContent()" />
									<MessageFace v-if="item.type === TYPES.MSG_FACE" :content="item.getMessageContent()"
										:isPC="isPC" />
									<MessageLocation v-if="item.type === TYPES.MSG_LOCATION"
										:content="item.getMessageContent()" />
									<MessageCustom v-if="item.type === TYPES.MSG_CUSTOM"
										:content="item.getMessageContent()" @openRedParket="openRedParket"
										:messageItem="item" />
								</MessageBubble>
							</div>
							<!--  @handleToggleMessageItem="handleToggleMessageItem"
								@handleH5LongPress="handleH5LongPress" 通话去掉撤回等事件 -->
								<!-- isRevoked是否被撤回 -->
							<MessagePlugin v-else-if="!item.isRevoked && isPluginMessage(item)" :message="item"
								@resendMessage="resendMessage" />
								<!-- 消息撤回通知组件 -->
							<MessageRevoked v-else :isEdit="item.type === TYPES.MSG_TEXT" :messageItem="item"
								@messageEdit="handleEdit(item)" />
							<MessageTool :class="[
                'message-tool',
                item.flow === 'out' ? 'message-tool-out' : 'message-tool-in',
              ]" :messageItem="item" v-if="item.ID === toggleID" />
						</div>
					</li>
				</scroll-view>
				<!-- 滚动按钮 -->
				<ScrollButton ref="scrollButtonInstanceRef" @scrollToLatestMessage="scrollToLatestMessage" />
				<Dialog v-if="reSendDialogShow" :show="reSendDialogShow" :isH5="!isPC" :center="true"
					:isHeaderShow="isPC" @submit="resendMessageConfirm()" @update:show="(e) => (reSendDialogShow = e)">
					<p class="delDialog-title">
						{{ TUITranslateService.t("TUIChat.确认重发该消息？") }}
					</p>
				</Dialog>

				<ImagePreviewer v-if="showImagePreview" :currentImage="currentImagePreview"
					:imageList="imageMessageList" @close="onImagePreviewerClose"></ImagePreviewer>
				<MessageGroupSystem v-if="showGroupApplication" :groupID="groupID"
					@toggleApplicationList="toggleApplicationList" @handleGroupApplication="handleGroupApplication">
				</MessageGroupSystem>
				<!-- 已读回执用户列表面板 -->
				<ReadReciptPanel v-if="isShowReadUserStatusPanel" :message="Object.assign({}, readStatusMessage)"
					@setReadReciptPanelVisible="setReadReciptPanelVisible" />
			</div>

		</div>
		<!-- 红包领取未领取弹窗 -->
		<!-- 领取红包 -->
		<u-popup v-if="redParketShow" :show="redParketShow" @close="redParketShow=false" bgColor="transparent"
			mode="center">
			<view class="content-box">
				<view class="win-box">
					<image class="red-wars" :src="redWars" />

					<view class="title">{{redParkInfo.remark}}</view>
					<image class="btn-red" :class="{ rotate: isRotated }" :src="redIconOpen" @tap="RedWars"></image>
					<view class="name">【{{redParkInfo.payType}}】红包</view>
				</view>
				<view class="icon-close" @tap="redParketShow=false">
					<u-icon name="close-circle" color="#F9DCBA" size="36"></u-icon>
				</view>
			</view>
		</u-popup>
		<!-- 已领取红包 -->
		<u-popup v-if="redUseParketShow" :show="redUseParketShow" @close="redUseParketShow=false" bgColor="transparent"
			mode="center">
			<view class="content-box">
				<view class="win-box">
					<image class="red-wars" :src="redWarsAct" />
					<view class="name name-top">【{{redParkInfo.payType}}】红包</view>
					<view class="user-info">
						<image :src="redParkInfo.currentUser.avatar||avatar" />
						<view class="nick">{{redParkInfo.currentUser.nick}}</view>
						<view>的红包</view>

					</view>
					<view class="price">
						<text>34</text>
						<text class="unit">元</text>
					</view>
					<view class="detail" @tap="toDetail">
						<view>领取详情</view>
						<u-icon name="arrow-right" color="#F9DCBA" size="32rpx"></u-icon>
					</view>
				</view>
				<view class="icon-close" @tap="redUseParketShow=false">
					<u-icon name="close-circle" color="#F9DCBA" size="36"></u-icon>
				</view>
			</view>
		</u-popup>
	</div>
</template>
<script lang="ts" setup>
	import redWars from "../../../assets/icon/redWars.png";
	import redWarsAct from "../../../assets/icon/redWarsAct.png";
	import redIconOpen from "../../../assets/icon/red-parker-icon.png";
	import {
		ref,
		computed,
		nextTick,
		onMounted,
		onUnmounted,
		getCurrentInstance,
	} from "../../../adapter-vue";
	import TUIChatEngine, {
		IMessageModel,
		TUIStore,
		StoreName,
		TUITranslateService,
		TUIChatService,
		TUIGroupService,
	} from "@tencentcloud/chat-uikit-engine";
	import throttle from "lodash/throttle";
	import {
		setInstanceMapping,
		getBoundingClientRect,
		getScrollInfo,
		TUIGlobal
	} from "@tencentcloud/universal-api";
	import avatar from "../../../assets/icon/head.png";
	import Link from "./link";
	import MessageText from "./message-elements/message-text.vue";
	import ProgressMessage from "../../common/ProgressMessage/index.vue";
	import MessageImage from "./message-elements/message-image.vue";
	import MessageAudio from "./message-elements/message-audio.vue";
	import MessageFile from "./message-elements/message-file.vue";
	import MessageFace from "./message-elements/message-face.vue";
	import MessageCustom from "./message-elements/message-custom.vue";
	import MessageTip from "./message-elements/message-tip.vue";
	import MessageBubble from "./message-elements/message-bubble.vue";
	import MessageLocation from "./message-elements/message-location.vue";
	import MessageTimestamp from "./message-elements/message-timestamp.vue";
	import MessageVideo from "./message-elements/message-video.vue";
	import MessageTool from "./message-tool/index.vue";
	import MessageRevoked from "./message-tool/message-revoked.vue";
	import MessageGroupSystem from "./message-elements/message-group-system.vue";
	import MessagePlugin from "../../../plugins/plugin-components/message-plugin.vue";
	import ReadReciptPanel from "./read-receipt-panel/index.vue";
	import ScrollButton from "./scroll-button/index.vue";
	import { isPluginMessage } from "../../../plugins/plugin-components/index";
	import Dialog from "../../common/Dialog/index.vue";
	import ImagePreviewer from "../../common/ImagePreviewer/index.vue";
	import { Toast, TOAST_TYPE } from "../../common/Toast/index";
	import { isCreateGroupCustomMessage } from "../utils/utils";
	import { isEnabledMessageReadReceiptGlobal } from "../utils/utils";
	import { isPC, isH5 } from "../../../utils/env";
	import { IAudioContext } from "../../../interface";
	import { checkUserInfo } from "../../../utils/checkLogin";
	import { staticPath } from '../../../utils/index'
	const props = defineProps({
		groupID: {
			type: String,
			default: "",
		},
		isGroup: {
			type: Boolean,
			default: false,
		},
	});
	
	
	
	
	let isRotated = ref(false)
	let pushMusic = uni.createInnerAudioContext()
	// pushMusic.obeyMuteSwitch = false
	pushMusic.src = staticPath + 'red-parket.mp3'


	let redUseParketShow = ref(false)
	let redParketShow = ref(false)
	let redParkInfo = ref({
		avatar: '',
		nick: ''
	})

	//领取红包
	const openRedParket = (e) => {
		redParkInfo.value = e.content
		redParketShow.value = true


	}
	//抢红包
	const RedWars = (e) => {
		pushMusic.play()
		isRotated.value = true
		setTimeout(() => {
			console.log(pushMusic)
			pushMusic.pause();
			isRotated.value = false
			// pushMusic.value = null
			redParketShow.value = false
			redUseParketShow.value = true
		}, 1000)

	}
	//查看红包领取列表
	const toDetail = () => {
		TUIGlobal?.navigateTo({
			url: '/pages/TUIKit/components/TUIChat/redPacket/detail?redParkInfo=' + JSON.stringify(redParkInfo.value)
		})
	}


	let observer : any = null;
	let groupType : string | undefined;
	const sentReceiptMessageID = new Set<string>();
	const thisInstance = getCurrentInstance()?.proxy || getCurrentInstance();
	const messageListRef = ref();
	const title = ref("TUIChat");
	const messageList = ref<Array<IMessageModel>>();
	const isCompleted = ref(false);
	const currentConversationID = ref("");
	const nextReqMessageID = ref();
	const toggleID = ref("");
	const scrollTop = ref(5000); // 首次是 15 条消息，最大消息高度为300
	const TYPES = ref(TUIChatEngine.TYPES);
	const listRef = ref();
	const isLoadMessage = ref(false);
	const isLongpressing = ref(false);
	const blinkMessageIDList = ref<string[]>([]);
	const messageTarget = ref<IMessageModel>();
	const scrollButtonInstanceRef = ref<InstanceType<typeof ScrollButton>>();
	let selfAddValue = 0;

	// audio control
	const globalAudioContext = ref<IAudioContext | null>(null);
	const broadcastNewAudioSrc = ref<string>("");

	// 阅读回执状态message
	const readStatusMessage = ref<IMessageModel>();
	const isShowReadUserStatusPanel = ref<boolean>(false);

	// 加群申请系统消息
	const groupApplicationCount = ref(0);
	const showGroupApplication = ref(false);
	const applicationUserIDList = ref([]);

	// 消息重发 Dialog
	const reSendDialogShow = ref(false);
	const resendMessageData = ref();
	const emits = defineEmits(["handleEditor"]);

	// 图片预览相关
	const showImagePreview = ref(false);
	const currentImagePreview = ref<IMessageModel>();
	const imageMessageList = computed(() =>
		messageList?.value?.filter((item : IMessageModel) => {
			return (
				!item.isRevoked &&
				!item.hasRiskContent &&
				item.type === TYPES.value.MSG_IMAGE
			);
		})
	);

	// 消息滑动到底部，建议搭配 nextTick 使用
	const scrollToBottom = () => {
		// 文本消息高度：60, 最大消息高度 280
		scrollTop.value += 300;
		// 解决 uniapp 打包到 app 首次进入滑动到底部，300 可设置
		const timer = setTimeout(() => {
			scrollTop.value += 1;
			clearTimeout(timer);
		}, 300);
	};

	// 监听回调函数
	const onCurrentConversationIDUpdated = (conversationID : string) => {
		currentConversationID.value = conversationID;
		TUIGroupService.getGroupApplicationList().then((res : any) => {
			const applicationList = res.data.applicationList.filter(
				(application : any) => application.groupID === props.groupID
			);
			applicationUserIDList.value = applicationList.map((application : any) => {
				return application.applicationType === 0
					? application.applicant
					: application.userID;
			});
			TUIStore.update(
				StoreName.CUSTOM,
				"groupApplicationCount",
				applicationList.length
			);
		});

		// 开启已读回执的状态 群聊缓存群类型
		if (isEnabledMessageReadReceiptGlobal()) {
			const { groupProfile } =
				TUIStore.getConversationModel(conversationID) || {};
			groupType = groupProfile?.type;
		}
	};

	// operationType 操作类型 1: 有用户申请加群   23: 普通群成员邀请用户进群
	const onGroupSystemNoticeList = (list : Array<IMessageModel>) => {
		const systemNoticeList = list.filter((message) => {
			const { operationType } = message.payload;
			return (
				(operationType === 1 || operationType === 23) &&
				message.to === props.groupID
			);
		});

		systemNoticeList.forEach((systemNotice) => {
			const { operationType } = systemNotice.payload;
			if (operationType === 1) {
				const { operatorID } = systemNotice.payload;
				if (!applicationUserIDList.value.includes(operatorID)) {
					applicationUserIDList.value.push(operatorID);
				}
			}
			if (operationType === 23) {
				const { inviteeList } = systemNotice.payload;
				inviteeList.forEach((invitee) => {
					if (!applicationUserIDList.value.includes(invitee)) {
						applicationUserIDList.value.push(invitee);
					}
				});
			}
		});
		const applicationCount = applicationUserIDList.value.length;
		TUIStore.update(StoreName.CUSTOM, "groupApplicationCount", applicationCount);
	};

	onMounted(() => {
		// 消息列表监听
		TUIStore.watch(StoreName.CHAT, {
			messageList: onMessageListUpdated,
			messageSource: onMessageSourceUpdated,
			isCompleted: onChatCompletedUpdated,
		});

		TUIStore.watch(StoreName.CONV, {
			currentConversationID: onCurrentConversationIDUpdated,
		});

		// 群系统消息
		TUIStore.watch(StoreName.GRP, {
			groupSystemNoticeList: onGroupSystemNoticeList,
		});

		// 群系统消息数量
		TUIStore.watch(StoreName.CUSTOM, {
			groupApplicationCount: onGroupApplicationCountUpdated,
		});
		setInstanceMapping("messageList", thisInstance);
	});

	// 取消监听
	onUnmounted(() => {
		TUIStore.unwatch(StoreName.CHAT, {
			messageList: onMessageListUpdated,
			isCompleted: onChatCompletedUpdated,
		});

		TUIStore.unwatch(StoreName.CONV, {
			currentConversationID: onCurrentConversationIDUpdated,
		});

		// 群系统消息
		TUIStore.unwatch(StoreName.GRP, {
			groupSystemNoticeList: onGroupSystemNoticeList,
		});

		TUIStore.unwatch(StoreName.CUSTOM, {
			groupApplicationCount: onGroupApplicationCountUpdated,
		});

		observer?.disconnect();
		observer = null;
	});

	const handelScrollListScroll = throttle(
		function (e : Event) {
			scrollButtonInstanceRef.value?.judgeScrollOverOneScreen(e);
		},
		500,
		{ leading: true }
	);

	function getGlobalAudioContext(
		audioMap : Map<string, IAudioContext>,
		options ?: { newAudioSrc : string }
	) {
		if (options?.newAudioSrc) {
			broadcastNewAudioSrc.value = options.newAudioSrc;
		}
	}

	async function onMessageListUpdated(list : IMessageModel[]) {
		console.log(list,"消息列表")
		observer?.disconnect();
		messageList.value = list
			.filter((message) => !message.isDeleted)
			.map((message) => {
				message.vueForRenderKey = `${message.ID}`;
				return message;
			});
		if (messageTarget.value) {
			// 存在需要滚动到该位置的目标消息，滚动到指定位置
			scrollAndBlinkMessage(messageTarget.value);
		} else if (!isLoadMessage.value) {
			// 点击加载更多的消息不需要滑动到底部
			nextTick(() => {
				scrollToBottom();
			});
		}
		if (isEnabledMessageReadReceiptGlobal()) {
			nextTick(() =>setTimeout(()=>{
				bindIntersectionObserver()
			},500));
		}
		//消息更新之前，检测是否已经登录了
		await checkUserInfo()
	}

	// 滚动到最新消息
	async function scrollToLatestMessage() {
		try {
			const { scrollHeight } = await getScrollInfo(
				"#messageScrollList",
				"messageList"
			);
			if (scrollHeight) {
				scrollTop.value === scrollHeight
					? (scrollTop.value = scrollHeight + 1)
					: (scrollTop.value = scrollHeight);
			} else {
				scrollToBottom();
			}
		} catch (error) {
			scrollToBottom();
		}
	}

	async function onMessageSourceUpdated(message : IMessageModel) {
		messageTarget.value = message;
		scrollAndBlinkMessage(messageTarget.value);
	}

	function scrollAndBlinkMessage(message : IMessageModel) {
		if (
			messageList.value?.some(
				(messageListItem) => messageListItem?.ID === message?.ID
			)
		) {
			nextTick(async () => {
				await scrollToTargetMessage(message);
				await blinkMessage(message?.ID);
				messageTarget.value = undefined;
			});
		}
	}

	function onChatCompletedUpdated(flag : boolean) {
		isCompleted.value = flag;
	}

	function onGroupApplicationCountUpdated(count : number) {
		groupApplicationCount.value = count;
	}

	// 获取历史消息
	const getHistoryMessageList = () => {
		isLoadMessage.value = true;
		TUIChatService.getMessageList().then((res : any) => {
			const { nextReqMessageID: ID } = res.data;
			nextReqMessageID.value = ID;
			isLoadMessage.value = false;
		});
	};

	const toggleApplicationList = () => {
		showGroupApplication.value = !showGroupApplication.value;
	};

	const handleGroupApplication = (userID : string) => {
		const index = applicationUserIDList.value.indexOf(userID);
		if (index !== -1) {
			applicationUserIDList.value.splice(index, 1);
		}
	};
	// todo: webview 跳转
	const openComplaintLink = (type : any) => { };

	// 消息操作
	const handleToggleMessageItem = (
		e : any,
		message : IMessageModel,
		index : number,
		isLongpress = false
	) => {
		if (isLongpress) {
			isLongpressing.value = true;
		}
		toggleID.value = message.ID;
	};

	// h5 long press
	let timer : number;
	const handleH5LongPress = (
		e : any,
		message : IMessageModel,
		index : number,
		type : string
	) => {
		if (!isH5) return;
		function longPressHandler() {
			clearTimeout(timer);
			handleToggleMessageItem(e, message, index, true);
		}
		function touchStartHandler() {
			timer = setTimeout(longPressHandler, 500);
		}
		function touchEndHandler() {
			clearTimeout(timer);
		}
		switch (type) {
			case "touchstart":
				touchStartHandler();
				break;
			case "touchend":
				touchEndHandler();
				setTimeout(() => {
					isLongpressing.value = false;
				}, 200);
				break;
		}
	};

	// 消息撤回后，编辑消息
	const handleEdit = (message : IMessageModel) => {
		emits("handleEditor", message, "reedit");
	};

	// 重发消息
	const resendMessage = (message : IMessageModel) => {
		reSendDialogShow.value = true;
		resendMessageData.value = message;
	};

	// 图片预览
	// 开启图片预览
	const handleImagePreview = (message : IMessageModel) => {
		console.log("图片预览",showImagePreview.value,currentImagePreview.value,isLongpressing.value)
		if (
			showImagePreview.value ||
			currentImagePreview.value ||
			isLongpressing.value
		) {
			return;
		}
		showImagePreview.value = true;
		currentImagePreview.value = message;

		console.log('currentImagePreview.valuecurrentImagePreview.valuecurrentImagePreview.value', currentImagePreview.value);
	};
	// 关闭图片预览
	const onImagePreviewerClose = () => {
		showImagePreview.value = false;
		setTimeout(() => {
			currentImagePreview.value = null;
		}, 50);
	};

	const resendMessageConfirm = () => {
		reSendDialogShow.value = !reSendDialogShow.value;
		const messageModel = resendMessageData.value;
		messageModel.resendMessage();
	};

	function blinkMessage(messageID : string) : Promise<void> {
		return new Promise((resolve) => {
			const index = blinkMessageIDList.value.indexOf(messageID);
			if (index < 0) {
				blinkMessageIDList.value.push(messageID);
				const timer = setTimeout(() => {
					blinkMessageIDList.value.splice(
						blinkMessageIDList.value.indexOf(messageID),
						1
					);
					clearTimeout(timer);
					resolve();
				}, 3000);
			}
		});
	}

	function scrollTo(scrollHeight : number) {
		scrollTop.value = scrollHeight;
	}

	async function bindIntersectionObserver() {
		if (messageList.value.length === 0) {
			return;
		}

		if (
			groupType === TYPES.value.GRP_AVCHATROOM ||
			groupType === TYPES.value.GRP_COMMUNITY
		) {
			// 直播群以及社群不进行消息的已读回执监听
			return;
		}
		
		

		observer?.disconnect();
		observer = uni
			.createIntersectionObserver(thisInstance, {
				thresholds: [0.7,1],
				observeAll: true,
				// uni 下会把 safetip 也算进去 需要负 margin 来排除
			})
			.relativeTo("#messageScrollList", { top: -70 });
		observer?.observe(".message-li.in .message-bubble-container", (res : any) => {
			
			if (sentReceiptMessageID.has(res.id)) {
				return;
			}
			// console.log(messageList.value,sentReceiptMessageID,"messageList")
			const matchingMessage = messageList.value.find((message : IMessageModel) => {
				return res.id.indexOf(message.ID) > -1;
			});
			console.log("matchingMessage当前这条消息",matchingMessage)
			if (
				matchingMessage &&
				matchingMessage.needReadReceipt &&
				matchingMessage.flow === "in" &&
				!matchingMessage.readReceiptInfo?.isPeerRead
			) {
				TUIChatService.sendMessageReadReceipt([matchingMessage]).catch((error : { message : string; code : number }) => {
					if (error.code === 20009) {
						Toast({
							message: '对方已不是你的好友',
							type: TOAST_TYPE.ERROR,
						})
					} else {
						Toast({
							message: error.message as string,
							type: TOAST_TYPE.ERROR,
						});
					}
				});
				sentReceiptMessageID.add(res.id);
			}
		});
	}

	function setReadReciptPanelVisible(visible : boolean, message ?: IMessageModel) {
		if (!visible) {
			readStatusMessage.value = undefined;
		} else {
			readStatusMessage.value = message;
		}
		isShowReadUserStatusPanel.value = visible;
	}

	async function scrollToTargetMessage(message : IMessageModel) {
		let targetMessageID = message.ID;
		const isTargetMessageInScreen =
			messageList.value &&
			messageList.value.some((msg) => msg.ID === targetMessageID);
		if (targetMessageID && isTargetMessageInScreen) {
			let timer = setTimeout(async () => {
				try {
					const scrollViewRect = await getBoundingClientRect(
						"#messageScrollList",
						"messageList"
					);
					const originalMessageRect = await getBoundingClientRect(
						"#tui-" + targetMessageID,
						"messageList"
					);
					const { scrollTop } = await getScrollInfo(
						"#messageScrollList",
						"messageList"
					);
					const finalScrollTop =
						originalMessageRect.top +
						scrollTop -
						scrollViewRect.top -
						(selfAddValue++ % 2);
					scrollTo(finalScrollTop);
					clearTimeout(timer);
				} catch (error) { }
			}, 500);
		} else {
			Toast({
				message: TUITranslateService.t("TUIChat.无法定位到原消息"),
				type: TOAST_TYPE.WARNING,
			});
		}
	}
</script>
<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
	.content-box {
		width: 518rpx;
		height: 750rpx;
	}

	.win-box {
		width: 518rpx;
		height: 700rpx;
		position: relative;
		z-index: 22;

		.red-wars {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
			z-index: -1;

		}

		.title {
			font-size: 36rpx;
			color: #F9DCBA;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			width: 100%;
			text-align: center;
			padding: 80rpx 20rpx 60rpx 20rpx;
			box-sizing: border-box;
		}

		.btn-red {
			width: 180rpx;
			height: 180rpx;
			margin: 0 auto;
			border-radius: 100%;
			transition: transform 1s;
			/* 设置过渡动画时长为1秒 */
			transform: rotate(0deg);
			/* 初始旋转角度为0度 */
		}
		.rotate {
		  transform: rotateY(360deg); /* 旋转到360度进行旋转动画 */
		}

		.name {
			position: absolute;
			bottom: 68rpx;
			width: 100%;
			text-align: center;
			color: #F9DCBA;
		}

		.user-info {
			display: flex;
			align-items: center;
			justify-content: center;
			color: #F9DCBA;
			font-size: 32rpx;
			padding-top: 200rpx;

			>image {
				width: 80rpx;
				height: 80rpx;
				border-radius: 100%;
				margin-right: 20rpx;
			}

			.nick {
				max-width: 37%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}

		.name-top {
			top: 68rpx;
			font-size: 36rpx;
		}

		.price {
			color: #F9DCBA;
			font-size: 70rpx;
			font-weight: 600;
			text-align: center;
			width: 100%;
			margin-top: 10rpx;

			.unit {
				font-size: 40rpx;
				margin-left: 8rpx;
				position: relative;
				top: -4rpx;
			}
		}

		.detail {
			color: #F9DCBA;
			display: flex;
			align-items: center;
			width: 100%;
			justify-content: center;
			position: absolute;
			bottom: 68rpx;
		}
	}

	.icon-close {
		width: 100%;
		display: flex;
		justify-content: center;
		margin-top: 30rpx;
	}

	::v-deep .u-popup {
		flex: 1;
		position: fixed;
		width: 100vh;
		height: 100vh;
		top: 0;
		left: 0;
		z-index: 6666;
	}
</style>